#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<pthread.h>
 //20191223
void* communication(void* arg);
 
int main()
{
	int sockfd=socket(PF_INET,SOCK_STREAM,0);
	assert(-1!=sockfd);
 
	struct sockaddr_in ser,cli;
	ser.sin_family=AF_INET;
	ser.sin_port=htons(6000);
	ser.sin_addr.s_addr=inet_addr("127.0.0.1");
	int res=bind(sockfd,(struct sockaddr*)&ser,sizeof(ser));
	assert(-1!=res);
 
	listen(sockfd,5);
 
	while(1)//保证服务器可以连接多个客户端
	{
		int len=sizeof(cli);
		int c=accept(sockfd,(struct sockaddr*)&cli,&len);
        if(c<0)
        {
            printf("link error\n");
            continue;
        }
 
		pthread_t id;
		int n=pthread_create(&id,NULL,communication,(void*)c);//创建线程，将文件描述符强转为void*，此处只能是值传递，地址传递的话，可能函数线程还没拿到该地址的值，就被主线程更改
		assert(n==0);
	}
    close(sockfd);
}
 
void* communication(void* arg)//函数线程完成与客户端的交互
{
	while(1)//实现与一个客户端的多次交互
	{
	    char buff[128]={0};
	    int c=(int)arg;//将文件描述符转回int型
	    int n=recv(c,buff,127,0);
	    if(n<=0)
	    {
			close(c);
			printf("%d client over\n",c);
			break;
	    }
	    printf("%d:%s\n",c,buff);
 
		send(c,"OK",2,0);
	}
}
